<template>
  <view class="p-20">
    <view class="my-card">
      <u-form :model="form" label-width="6em" ref="formRef">
        <u-form-item label="规格" prop="attributes">
          <view class="attr-container">
            <view
              class="attr-item"
              v-for="(attr, index) in form.attributes"
              :key="index"
            >
              <text class="attr-key">{{ attr.key }}：</text>
              <text class="attr-value">{{ attr.value }}</text>
              <u-icon
                name="close"
                size="18"
                color="#f56c6c"
                @click="removeAttr(index)"
              ></u-icon>
            </view>
            <view class="attr-add">
              <u-input
                v-model="newAttr.key"
                placeholder="规格名称"
                clearable
                border="bottom"
              />
              <u-input
                v-model="newAttr.value"
                placeholder="规格值"
                clearable
                border="bottom"
              />
              <view style="width: 6em">
                <u-button
                  size="mini"
                  type="primary"
                  @click="addAttr"
                  :disabled="!newAttr.key || !newAttr.value"
                >
                  添加
                </u-button>
              </view>
            </view>
          </view>
        </u-form-item>
        <u-form-item label="条形码" prop="barcode">
          <u-input
            v-model="form.barcode"
            placeholder="请输入条形码"
            clearable
          />
        </u-form-item>

        <u-form-item label="标准价格" prop="stand_price">
          <u-input
            v-model="form.stand_price"
            placeholder="请输入标准价格"
            clearable
          />
        </u-form-item>

        <u-form-item label="销售价格" prop="sale_price">
          <u-input
            v-model="form.sale_price"
            placeholder="请输入销售价格"
            clearable
          />
        </u-form-item>

        <u-form-item label="指导价格" prop="guiding_price">
          <u-input
            v-model="form.guiding_price"
            placeholder="请输入指导价格"
            clearable
          />
        </u-form-item>

        <u-form-item label="重量(kg)" prop="weight">
          <u-input v-model="form.weight" placeholder="请输入重量" clearable />
        </u-form-item>

        <u-form-item label="体积(m³)" prop="volume">
          <u-input v-model="form.volume" placeholder="请输入体积" clearable />
        </u-form-item>

        <u-form-item label="库存" prop="stock">
          <u-input v-model="form.stock" placeholder="请输入库存" clearable />
        </u-form-item>

        <u-form-item label="规格图片" prop="image_url">
          <u-upload
            :maxCount="1"
            :fileList="files"
            @afterRead="afterRead"
            @delete="deletePic"
            name="file"
            :previewFullImage="true"
          ></u-upload>
        </u-form-item>

        <u-button type="primary" @click="handleSubmit">提交</u-button>
      </u-form>
    </view>
  </view>
</template>

<script setup>
import {
  addVariants,
  getVariantsDetail,
  editVariants,
} from "@/common/apis/goods.js";
import { uploadFile } from "@/common/apis/common.js";
import { onShow } from "@dcloudio/uni-app";
import { reactive, ref } from "vue";

const props = defineProps({
  product_id: String,
  variant_id: String,
  type: String,
});

const formRef = ref();
const files = ref([]);

const form = reactive({
  product_id: props.product_id,
  variant_id: props.variant_id,
  barcode: "",
  stand_price: "",
  sale_price: "",
  guiding_price: "",
  weight: "",
  volume: "",
  stock: "",
  image_url: "",
  attributes: [],
});

const newAttr = reactive({
  key: "",
  value: "",
});

async function fetchSkuDetail() {
  const response = await getVariantsDetail(props.product_id, props.variant_id);
  if (response) {
    form.barcode = response.barcode || "无";
    form.stand_price = response.stand_price;
    form.sale_price = response.sale_price;
    form.guiding_price = response.guiding_price;
    form.weight = response.weight;
    form.volume = response.volume;
    form.attributes = response.attributes || [];
    form.image_url = response.image_url;
    form.stock = response.stock;

    if (response.image_url) {
      files.value = [
        {
          url: response.image_url,
          status: "success",
          message: "",
        },
      ];
    }
  }
}

async function afterRead(event) {
  // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
  let lists = [].concat(event.file);
  let fileListLen = files.value.length;
  lists.map((item) => {
    files.value.push({
      ...item,
      status: "uploading",
      message: "上传中",
    });
  });
  for (let i = 0; i < lists.length; i++) {
    const result = await uploadFile(lists[i].url);
    let item = files.value[fileListLen];
    files.value.splice(
      fileListLen,
      1,
      Object.assign(item, {
        status: "success",
        message: "",
        url: result.url,
      })
    );
    form.image_url = result.url;
    fileListLen++;
  }
}

function deletePic(event) {
  // 处理图片删除逻辑
  form.image_url = "";
  files.value = [];
}

async function handleSubmit() {
  // 处理表单提交逻辑
  if (props.type == "edit") {
    const response = await editVariants(form);
    if (response) {
      uni.showModal({
        title: "提示",
        content: "编辑成功",
        showCancel: false,
        success: () => {
          uni.navigateBack({
            delta: 1,
          });
        },
      });
    }
    return;
  } else if (props.type == "add") {
    const response = await addVariants(form);
    if (response) {
      uni.showModal({
        title: "提示",
        content: "添加成功",
        showCancel: false,
        success: () => {
          uni.navigateBack({
            delta: 1,
          });
        },
      });
    }
  }
}

onShow(async () => {
  if (props.type == "edit") {
    await fetchSkuDetail();
  }
});

function addAttr() {
  form.attributes.push({ ...newAttr });
  newAttr.key = "";
  newAttr.value = "";
}

function removeAttr(index) {
  form.attributes.splice(index, 1);
}
</script>
<style lang="scss" scoped>
.attr-container {
  width: 100%;
}

.attr-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding: 8px 12px;
  background-color: #f5f5f5;
  border-radius: 4px;

  .attr-key {
    font-weight: bold;
    color: #333;
    margin-right: 5px;
  }

  .attr-value {
    color: #666;
    margin-right: 10px;
  }
}

.attr-add {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 15px;

  .u-input {
    flex: 1;
  }
}
</style>
